﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 用于收集电压电流有功的数据 和 一些电气事件 并进行提示
/// </summary>
public class Multimeter : MonoBehaviour {
    public Text voltage;
    public Text current;
    public Text power;
    [SerializeField]
    private string uReg = "u([0-9]{1,}[.]?[0-9]*)";
    [SerializeField]
    private string iReg = "i([0-9]{1,}[.]?[0-9]*)";
    [SerializeField]
    private string pReg = "p([0-9]{1,}[.]?[0-9]*)";

    /// <summary>
    /// 电气故障表。key为匹配的字符串，value为显示的字串
    /// </summary>
    public List<KPair> powerFailures;


    // Use this for initialization
    void Start () {
        MCNetSocket.OnRec += (data, count) =>
        {
            string s = Encoding.ASCII.GetString(data,0, count);
            if(Regex.IsMatch(s,uReg))
            voltage.text = T.getMatch(s, uReg);
            if(Regex.IsMatch(s,iReg))
            current.text = T.getMatch(s, iReg);
            if(Regex.IsMatch(s,pReg))
            power.text = T.getMatch(s, pReg);
   
            foreach (var p in powerFailures)
            {
                if (Regex.IsMatch(s,p.key))
                {
                    Toast.Show(p.value);
                }
            }
        };
	}


}

public static class T
{
    public static string getMatch(string s, string reg)
    {
        Regex getter = new Regex(reg);
        Match mat = getter.Match(s);
        return mat.Groups[1].Value;
    }

}
[System.Serializable]
public class KPair
{
    public string key;
    public string value;
}